package com.yserp.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.security.ShiroUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author carl
 * @date 2022年07月22日 12:00
 */
@Component
public class CreateAndUpdateEntityHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            //根据属性名字设置要填充的值
            if (metaObject.hasGetter("createTime")) {
                if (metaObject.getValue("createTime") == null) {
                    this.setFieldValByName("createTime", new Date(), metaObject);
                }
            }

            // 正式启用式启用再添加这个
            if (metaObject.hasGetter("createBy")) {
                if (metaObject.getValue("createBy") == null) {
                    this.setFieldValByName("createBy", ShiroUtils.getLoginName(), metaObject);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            // 正式启用式启用再添加这个
            if (metaObject.hasGetter("updateBy")) {
                if (metaObject.getValue("updateBy") == null) {
                    this.setFieldValByName("updateBy", ShiroUtils.getLoginName(), metaObject);
                }
            }

            if (metaObject.hasGetter("updateTime")) {
                if (metaObject.getValue("updateTime") == null) {
                    this.setFieldValByName("updateTime", new Date(), metaObject);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
